var socket;
var stompClient = null;
var intervalTimeID = 0;

$(function () {
    disconnect();
    stompConnect();
});

function stompConnect() {
    socket = new SockJS('/endpoint');
    clearInterval(intervalTimeID);
    stompClient = Stomp.over(socket);
    stompClient.debug = "false";
    stompClient.heartbeat.outgoing = 8000;
    stompClient.heartbeat.incoming = 8000;
    stompClient.connect("","", stompSuccessCallback, stompFailureCallback);
}

function stompSuccessCallback() {
    stompClient.subscribe('/user/queue/original', function (msg) {
        try{
            if (PjaxApp.extractPageName(location.href) == "login" && msg != null && msg.body != "") {
                processDate(jQuery.parseJSON(msg.body));
            }
        }catch(err){
            // console.info(err);
        }
    });
    stompClient.subscribe('/user/topic/warning', function (msg) {
        if (PjaxApp.extractPageName(location.href) == "login" && msg != null && msg.body != "") {
            processWarningData(jQuery.parseJSON(msg.body));
        }
    });

}


var stompFailureCallback = function (error) {
    console.log('STOMP: ' + error);
    disconnect();
    intervalTimeID = setInterval(stompConnect, 2000);
    console.log('STOMP: Reconecting in 2 seconds');
};

function disconnect() {
    if (stompClient != null) {
        stompClient.disconnect();
        console.log("Disconnected");
    }
}

